package com.nineclock.document.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itzhanshen.sys.feign.SysUserFeign;
import com.nineclock.common.entity.PageResult;

import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NCException;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.common.utils.CurrentUserHolder;
import com.nineclock.document.dto.DocFileDto;
import com.nineclock.document.dto.DocFileHistoryDto;
import com.nineclock.document.mapper.DocCollaborationsMapper;
import com.nineclock.document.mapper.DocFileHistoryMapper;
import com.nineclock.document.mapper.DocFileMapper;
import com.nineclock.document.pojo.DocCollaborations;
import com.nineclock.document.pojo.DocFile;
import com.nineclock.document.pojo.DocFileHistory;
import com.nineclock.document.service.PCDocumentService;
import com.nineclock.dto.SysCompanyUserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class PCDocumentServiceImpl implements PCDocumentService {
    @Autowired
    DocFileMapper docFileMapper;

    @Autowired
    SysUserFeign sysUserFeign;
    @Autowired
    DocCollaborationsMapper docCollaborationsMapper;
    @Autowired
    DocFileHistoryMapper docFileHistoryMapper;

    /**
     * 分页查询文档列表
     *
     * @param page
     * @param pageSize
     * @param keyword
     * @return
     */
    @Override
    public PageResult<DocFileDto> pagingFile(Integer page, Integer pageSize, String keyword) {
        Long companyId = CurrentUserHolder.get().getCompanyId();
        // 组装查询条件
        Page<DocFile> pages = new Page<>(page, pageSize);
        LambdaQueryWrapper<DocFile> wrapper = new LambdaQueryWrapper<>();
        // 构建查询条件
        wrapper.eq(DocFile::getCompanyId, companyId);
        // 增加关键字查询条件
        if (StrUtil.isNotEmpty(keyword)) {
            wrapper.eq(DocFile::getName, keyword);
        }
        //wrapper.eq(DocFile::getStatus, (short) 1);
        pages = docFileMapper.selectPage(pages, wrapper);
        // 查询文档列表
        List<DocFile> docFiles = pages.getRecords();
        if (docFiles != null) {
            List<DocFileDto> docFileDtos = BeanHelper.copyWithCollection(docFiles, DocFileDto.class);
            // 封装数据
            for (DocFileDto docFileDto : docFileDtos) {
                // 获取创建人Id
                Long createUserId = docFileDto.getCreateUserId();
                // 根据id查询信息
                SysCompanyUserDTO companyUserDTO = sysUserFeign.findCompanyUserById(createUserId).getData();
                // 封装创建文档者信息
                docFileDto.setCreator(companyUserDTO);
                // 根据文档iD查询协作者
                LambdaQueryWrapper<DocCollaborations> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(DocCollaborations::getFileId, docFileDto.getId());
                List<DocCollaborations> docCollaborations = docCollaborationsMapper.selectList(queryWrapper);
                if (docCollaborations != null) {
                    // 该文档的所有协作者ID
                    List<Long> collaborationIds = docCollaborations.stream().map(docCollaborations1 -> {
                        return docCollaborations1.getCollaborationId();
                    }).collect(Collectors.toList());
                    List<SysCompanyUserDTO> companyUserDTOS = new ArrayList<>();
                    for (Long collaborationId : collaborationIds) {
                        SysCompanyUserDTO data = sysUserFeign.findCompanyUserById(collaborationId).getData();
                        if (data != null)
                            companyUserDTOS.add(data);
                    }
                    // 封装协作者
                    docFileDto.setCollaborations(companyUserDTOS);
                    // 组装用户名和最后更新人Id
                    docFileDto.setUpdateUserName(companyUserDTO.getUserName());
                    docFileDto.setUpdateUserId(companyUserDTO.getUserId());
                }

            }
            return new PageResult<>(pages.getTotal(), pages.getPages(), docFileDtos);
        }
        return null;
    }

    /**
     * 更改文档权限
     *
     * @param fileId
     * @param status
     */
    @Override
    public void updateAuthority(Long fileId, Short status) {
        // 参数校验
        if (fileId == null || status == null) {
            throw new NCException(ResponseEnum.MESSAGE_PARAMS_LOST);
        }
        // 根据文档id查询文档
        DocFile docFile = docFileMapper.selectById(fileId);
        if (docFile != null) {
            // 修改查询到的文档权限
            docFile.setStatus(status);
            docFileMapper.updateById(docFile);
        }
    }

    /**
     * 查询文档历史记录
     *
     * @param fileId
     * @return
     */
    @Override
    public List<DocFileHistoryDto> queryFileHistory(Long fileId) {
        // 校验参数
        if (fileId != null) {
            // 根据文档ID查询历史记录
            List<DocFileHistory> docFileHistoryList = docFileHistoryMapper.queryFileHistoryByFileId(fileId);
            if (docFileHistoryList != null) {
                List<DocFileHistoryDto> docFileHistoryDtos = BeanHelper.copyWithCollection(docFileHistoryList, DocFileHistoryDto.class);
         /*       List<Long> OperateUserIds = docFileHistoryDtos.stream().map(docFileHistoryDto -> {
                    return docFileHistoryDto.getOperateUserId();*/
                //}).collect(Collectors.toList());
                docFileHistoryDtos.stream().forEach(docFileHistoryDto -> {

                    // 根据操作人ID查询员工信息
                    SysCompanyUserDTO companyUserDTO = sysUserFeign.findCompanyUserById(docFileHistoryDto.getOperateUserId()).getData();
                    if (companyUserDTO != null) {
                        // 组装数据
                        docFileHistoryDto.setUserName(companyUserDTO.getUserName());
                    }
                });
                return docFileHistoryDtos;
            }
        }

        return null;
    }
}
